import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { Subscription } from 'rxjs';

import { CommonService } from '../../core/services/common.service';
import { ValidatorFactoryService } from '../../core/services/validator-factory.service';

declare const $: any;

@Component({
    templateUrl: './float-input-reactive-form.component.html',
    styleUrls: ['../../../assets/styles/hide-element-focus-outline.css']
})
export class FloatInputReactiveFormComponent implements AfterViewInit, OnInit, OnDestroy {
    data: any;
    gender: any[];
    formGroup: FormGroup;
    private passwordSubscription: Subscription;

    constructor(
        private commonService: CommonService,
        private elementRef: ElementRef,
        private formBuilder: FormBuilder,
        private validatorFactory: ValidatorFactoryService
    ) { }

    ngOnInit(): void {
        this.data = {
            id: 1,
            name: 'Tesla Model 3',
            password: '111111',
            confirmPassword: '111111',
            gender: {
                id: 0,
                text: 'Girl'
            },
            age: 18,
            likeBeef: false,
            states: null
        };

        this.gender = [
            {
                id: 0,
                text: 'Girl'
            },
            {
                id: 1,
                text: 'Boy'
            }
        ];

        this.createForm();
        this.loadData();
    }

    ngAfterViewInit(): void {
        this.commonService.appendScriptChildToElement(this.elementRef, ['js/custom-form-float.js']);
    }

    ngOnDestroy(): void {
        this.passwordSubscription.unsubscribe();
    }

    confirm(): void {
        console.log('Confirmed');
    }

    cancel(): void {
        console.log('Canceled');
    }

    onSubmit(): void {
        console.log(`Prechanged: ${this.data}. Postchanged: ${this.formGroup.value}`);
    }

    private createForm(): void {
        this.formGroup = this.formBuilder.group({
            name: ['', [
                Validators.required,
                this.validatorFactory.getForbiddenValueValidator(/test/i),
                Validators.minLength(4)
            ]],
            age: ['', [
                Validators.required,
                Validators.min(18),
                Validators.max(100)
            ]],
            password: ['', [
                Validators.required,
                Validators.minLength(6)
            ]],
            confirmPassword: ['']
        }, {
            validators: this.validatorFactory.getValueNotMatchValidator(['password', 'confirmPassword'])
        });
    }

    private loadData(): void {
        this.formGroup.setValue({
            name: this.data.name,
            age: this.data.age,
            password: this.data.password,
            confirmPassword: this.data.confirmPassword
        });
    }
}